/**
 * Created by Administrator on 2015/12/4.
 */
"use strict";
var F = require('../../../common/function');
var organization_F = require('./organization_common');
var _o2oServiceApi = require('../../../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;
var _ = require('underscore');

exports.add_organization = function*(organization, key_validate_array) {
  let error_msg = organization_F.validateOrganizationFields(organization, key_validate_array);
  if (error_msg != '') {
    return F.returnMsg(400, error_msg, 1);
  }
  organization.act = 3;//后台录入机构
  organization.status = 0;//创建时默认无效，CallBack时将其设为有效
  if (organization.district && !_.isEmpty(organization.district)) {
    organization.disCodes = yield F.array_2_codeArray(organization.district, 'code');
    delete organization.district;
  }
  //organization.loc = [parseFloat(organization.lng), parseFloat(organization.lat)];
  //delete organization.lng;
  //delete organization.lat;
  //organization.tel = organization.tel.split(',');
  let organizaitonResult = yield o2oServiceApi.post('shop', 'add', 1, organization);
  if (parseInt(organizaitonResult['result']['error']) == 1 || organizaitonResult.status == 400) {
    //如果该机构存在
    if (organizaitonResult.status == 400 && organizaitonResult['result']['thereHaveBeenData'] && organizaitonResult['result']['thereHaveBeenData'] == 1) {
      if (organizaitonResult['result']['status'] == 1) {
        return F.returnMsg(300, '数据库存在同名机构，请先修改机构名字', 1);
      }
      organization.id = organizaitonResult['result']['id'];
      yield organization_F.generate_img_signature(organization);
      let upYunSign = organization.upYunSign;
      organization.act = 1;
      organizaitonResult = yield o2oServiceApi.post('shop', 'update', 1, organization);
      if (!_.isEmpty(upYunSign)) {
        organizaitonResult['result'].upYunSign = upYunSign;
      }
      return F.returnMsg(200, '保存成功', 1, organizaitonResult['result']);
    }
    else {
      return F.returnMsg(300, organizaitonResult['message']['msg'], 1);
    }
  } else {
    yield organization_F.generate_img_signature(organizaitonResult['result']);
    let upYunSign = organizaitonResult['result'].upYunSign;
    organizaitonResult['result'].act = 1;
    organizaitonResult = yield o2oServiceApi.post('shop', 'update', 1, organizaitonResult['result']);
    organizaitonResult['result'].upYunSign = upYunSign;
    return F.returnMsg(200, '保存成功', 1, organizaitonResult['result']);
  }
};